package com.itheima.service.impl;

import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Dept;
import com.itheima.pojo.DeptLog;
import com.itheima.service.DeptLogService;
import com.itheima.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private DeptLogService deptLogService;

    //查询所有部门的信息
    @Override
    public List<Dept> list() {
        //调用mapper层的方法并返回给controller层
        return deptMapper.list();
    }

    //根据id删除部门
    @Override
    @Transactional(rollbackFor = Exception.class)
    //将此方法交给spring进行事务管理,但是此注解只能回滚运行时的异常
    //加上后面的属性之后会指定回滚哪些异常,Exception.class代表会回滚所有异常
    public void deleteById(Integer id) {
        try {
            deptMapper.deleteById(id);
            //根据部门id删除部门下的员工信息
            log.info("根据部门id删除部门下的员工信息");
            empMapper.deleteEmpByDeptId(id);
        } finally {
            DeptLog log = new DeptLog();
            log.setCreateTime(LocalDateTime.now());
            log.setDescription("执行了解散部门的操作,此次解散的部门是"+id+"号部门");
            //记录操作日志
            deptLogService.insert(log);
        }
    }

    //新增部门
    @Override
    public void insertDept(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.insertdept(dept);
    }

    //根据id查询部门
    @Override
    public Dept selectDeptById(Integer id) {
        return deptMapper.selectDeptById(id);
    }

    //修改部门信息
    @Override
    public void updateDept(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.updateDept(dept);
    }

}
